//
//  LXComposePictureView.swift
//  weibo
//
//  Created by lixin on 16/4/23.
//  Copyright © 2016年 lixin. All rights reserved.
//

import UIKit

private let LXComposePictureViewCellId = "pictureViewCellId"

class LXComposePictureView: UICollectionView {
    
    var composePictureViewClosure: (()->())?
    
    var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 供外界调用方法
    
    //添加图片
    func addImage(image: UIImage){
        
        images.insert(image, atIndex: 0)
       
        if images.count > 9{
            
            images.removeLast()
        }
        
        if images.count > 0{
            
            self.hidden = false
        }
       
        reloadData()
    }
    
    // MARK: - 设置视图
    private func setUI(){
        
        self.backgroundColor = UIColor.whiteColor()
        
        self.hidden = true
        
        dataSource = self
        
        delegate = self
        
        registerClass(LXComposePictureViewCell.self, forCellWithReuseIdentifier: LXComposePictureViewCellId)
        
        let margin: CGFloat = 5
        
        let cellWH = (SCREENW - 20 - margin * 2) / 3
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
       
        layout.minimumLineSpacing = margin
        
        layout.minimumInteritemSpacing = margin
    }
    
}

// MARK: - UICollectionView代理和数据源方法
extension LXComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = images.count
        
        if count == 0 || count == 9{
            
            return count
            
        }else{
            
            return count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LXComposePictureViewCellId, forIndexPath: indexPath) as! LXComposePictureViewCell
        
        if indexPath.item == images.count{
            
            cell.image = nil
            
        }else{
            
            cell.image = images[indexPath.item]
        }
        
        cell.composePictureViewCellClosure = {[weak self] in
            
            self?.images.removeAtIndex(indexPath.item)
            
            if self?.images.count <= 0{
                
                self?.hidden = true
            }
            
            self?.reloadData()
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if indexPath.item == images.count{
            
            composePictureViewClosure?()
        }
    }
}

// 自定义cell
class LXComposePictureViewCell: UICollectionViewCell {
    
    var composePictureViewCellClosure: (()->())?
    
    var image: UIImage?{
        
        didSet{

            if image != nil{
                
                bgImageView.image = image
                
                bgImageView.highlightedImage = nil
               
                deleteButton.hidden = false
                
            }else{
                
                bgImageView.image = UIImage(named: "compose_pic_add")
                
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
                deleteButton.hidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setUI(){
        
        self.backgroundColor = UIColor.whiteColor()
       
        contentView.addSubview(bgImageView)
        
        contentView.addSubview(deleteButton)
       
        bgImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(contentView)
            
            make.trailing.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView()
    
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton()
        
        button.addTarget(self, action: #selector(LXComposePictureViewCell.deleteButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return button
        
    }()
    
    // MARK: - 点击事件
    @objc private func deleteButtonClick(){
        
        composePictureViewCellClosure?()
    }
    
}
